﻿using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;

namespace DynamicGeometry
{
    public class DrawingSerializer
    {
#if !SILVERLIGHT
        public static void Save(Drawing drawing, string fileName)
        {
            string serialized = SaveDrawing(drawing);
            File.WriteAllText(fileName, serialized);
        }
#endif

        public static void SaveDrawing(Drawing drawing, XmlWriter writer)
        {
            writer.WriteStartDocument();
            writer.WriteStartElement("Drawing");
            WriteFigureList(drawing.GetSerializableFigures(), writer);
            writer.WriteEndElement();
            writer.WriteEndDocument();
        }

        public static string SaveDrawing(Drawing drawing)
        {
            var s = new StringBuilder();
            using (var w = XmlWriter.Create(s, new XmlWriterSettings()
            {
                Indent = true
            }))
            {
                SaveDrawing(drawing, w);
            }
            return s.ToString();
        }

        public static void WriteFigureList(IEnumerable<IFigure> list, XmlWriter writer)
        {
            writer.WriteStartElement("Figures");
            foreach (var figure in list)
            {
                WriteFigure(figure, writer);
            }
            writer.WriteEndElement();
        }

        private static void WriteFigure(IFigure figure, XmlWriter writer)
        {
            writer.WriteStartElement(GetTagNameForFigure(figure));
            writer.WriteAttributeString("Name", figure.Name);
            figure.WriteXml(writer);
            WriteDependencies(figure, writer);
            writer.WriteEndElement();
        }

        private static void WriteDependencies(IFigure figure, XmlWriter writer)
        {
            if (figure.Dependencies.IsEmpty())
            {
                return;
            }
            foreach (var item in figure.Dependencies)
            {
                writer.WriteStartElement("Dependency");
                writer.WriteAttributeString("Name", item.Name);
                writer.WriteEndElement();
            }
        }

        private static string GetTagNameForFigure(IFigure figure)
        {
            return figure.GetType().Name;
        }
    }
}
